import React, { Key, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { Button, Form, Input, Card, Table } from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";

import {
  getHosSetListRequest,
  deleteHosSetRequest,
  batchRemoveHosSetRequest,
} from "@/api/hospital/hospitalSet";

import type {
  getHosSetListItemType,
  getHosSetRecordsType,
} from "@/api/hospital/model/hospitalSetTypes";
import style from "./index.module.css";

interface searchFormType {
  hosname: string;
  hoscode: string;
}

export default function HospitalSet() {
  const navigate = useNavigate();

  const [hosSetList, setHosSetList] = useState<getHosSetRecordsType>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(3);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [search, setSearch] = useState<searchFormType>();
  const [reRender, setReRender] = useState(false);
  const [Ids, setIds] = useState<Key[]>([]);
  const [isBatchBtn, setIsBatchBtn] = useState(true);
  useEffect(() => {
    setIsLoading(true);
    const getHosSetList = async () => {
      const re = await getHosSetListRequest({
        page: current,
        limit: pageSize,
        ...search,
      });
      setHosSetList(re.records);
      setTotal(re.total);
      setIsLoading(false);
    };
    getHosSetList();
  }, [current, pageSize, search, reRender]);

  const columns = [
    {
      title: "#",
      dataIndex: "index",
      width: 50,
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIdex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIdex: "contactsPhone",
    },
    {
      title: "操作",
      dataIdex: "handle",
      fixed: "right" as "right",
      width: 120,
      render(_: any, value: getHosSetListItemType) {
        const { id } = value;
        return (
          <div className={style.minButtons}>
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => {
                navigate(`/syt/hospital/updatehosset/${id}`);
              }}
            />
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={deleteHosSetHandle(id)}
            />
          </div>
        );
      },
    },
  ];

  const searchHandle = (fieldValue: searchFormType) => {
    setSearch(fieldValue);
  };

  const deleteHosSetHandle = (id: number) => {
    return async () => {
      await deleteHosSetRequest(id);
      setReRender(!reRender);
    };
  };

  return (
    <div className={style.outer}>
      <Card>
        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout="inline"
          onFinish={searchHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              <SearchOutlined />
              搜索
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>

        <div className={style.buttons}>
          <Button
            type="primary"
            onClick={() => {
              navigate("/syt/hospital/addhosset");
            }}
          >
            添加
          </Button>
          <Button
            type="primary"
            danger
            disabled={isBatchBtn}
            onClick={() => {
              batchRemoveHosSetRequest(Ids);
              setReRender(!reRender);
              setIsBatchBtn(true);
            }}
          >
            批量删除
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={hosSetList}
          rowKey="id"
          scroll={{ x: 1500 }}
          bordered
          loading={isLoading}
          rowSelection={{
            onChange(ids: Key[]) {
              setIds(ids);
              setIsBatchBtn(!ids.length);
            },
          }}
          //给表格的配置页码，通过对象配置
          pagination={{
            //当前页码
            current,
            //数据的数量
            total,
            //每页多少条
            pageSize,
            //展示更改每页条数的选项（默认total大于50条的时候开启）
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal() {
              return `共${total}条数据`;
            },
            onChange(current: number, pageSize: number) {
              setCurrent(current);
              setPageSize(pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
